package com.sophialex.health.record.common.util;

import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Text;

import com.sophialex.health.record.common.view.RecordBaseView;
import com.sophialex.health.system.frame.widgets.custom.DigitalText;

public class JumpListener implements Listener {

	Control[] tabList;
	RecordBaseView view;

	public JumpListener(Control[] tabList, RecordBaseView view) {
		this.tabList = tabList;
		this.view = view;
	}

	public JumpListener(Control[] tabList) {
		this.tabList = tabList;
	}

	public void handleEvent(Event event) {
		switch (event.type) {
		case SWT.Traverse:
		case SWT.KeyDown:
			doJump(event);
			break;
		default:
			break;
		}
	}

	/**
	 * 跳转
	 * 
	 * @param event
	 */
	private void doJump(Event event) {
		Control control = (Control) event.widget;
		switch (event.keyCode) {
		case SWT.CR:
		case SWT.KEYPAD_CR:
		case SWT.ARROW_DOWN:
			doJumpNext(control);
			break;
		case SWT.ARROW_UP:
			doJumpUp(control);
			break;
		default:
			break;
		}
	}

	private void doJumpUp(Control control) {
		int i = 0;
		for (i = 0; i < tabList.length; i++) {
			if (control == tabList[i]) {
				break;
			}
		}
		while (i > 0) {
			i--;
			if (setFocusControl(tabList[i]))
				break;

		}
	}

	private boolean setFocusControl(Control control) {
		if (control == null || control.isDisposed() || !control.getVisible()
				|| !control.getEnabled())
			return false;
		if (control.getClass() == Text.class) {
			if (((Text) control).getEditable()) {
				((Text) control).setFocus();
				((Text) control).selectAll();
				return true;
			}
		} else {
			if (view != null) {
				view.doTableAdd(control);
			}
			return control.setFocus();
		}
		return false;
	}

	private void doJumpNext(Control control) {
		int i = 0;
		for (i = 0; i < tabList.length; i++) {
			if (tabList[i].getClass() == DigitalText.class
					&& control == ((DigitalText) tabList[i])._getText()) {
				break;
			} else if (control == tabList[i]) {
				break;
			}
		}
		while (i < tabList.length - 1) {
			i++;
			if (setFocusControl(tabList[i]))
				break;
		}
	}
}
